<template>
  <a-modal :maskClosable="false" :open="visible" :title="isEditing ? '编辑书签' : '添加书签'" @ok="handleOk" @cancel="$emit('update:open', false)" @update:open="$emit('update:open', $event)">
    <div class="bookmark-preview">
      <div class="bookmark-item">
        <div class="bookmark-header">
          <img v-if="previewFavicon" :src="previewFavicon" :alt="form.title" class="bookmark-icon" @error="handleIconError" ref="iconRef" />
          <span v-else-if="iconFailed" class="bookmark-icon default-icon" title="默认图标">
            <global-outlined />
          </span>
          <span v-else class="bookmark-icon loading-icon">
            <loading-outlined spin />
          </span>
          <div class="bookmark-title">{{ form.title || '书签标题' }}</div>
        </div>
        <div class="bookmark-footer">
          <a-tooltip v-if="form.description" :title="form.description" placement="bottom">
            <div class="bookmark-description">
              {{ form.description || form.url || '书签链接' }}
            </div>
          </a-tooltip>
          <div v-else class="bookmark-description">
            {{ form.url || '书签链接' }}
          </div>
          <div class="bookmark-actions">
            <edit-outlined class="action-icon" @click="$emit('edit', form)" />
            <a-popconfirm title="确定要删除这个书签吗？" description="此操作不可恢复" @confirm="confirmDelete">
              <delete-outlined class="action-icon" />
            </a-popconfirm>
          </div>
        </div>
      </div>
    </div>

    <a-form :model="form" layout="vertical">
      <a-form-item label="标题" name="title">
        <a-input v-model:value="form.title" placeholder="请输入书签标题" />
      </a-form-item>
      <a-form-item label="URL" name="url">
        <a-input v-model:value="form.url" placeholder="请输入书签链接" />
      </a-form-item>
      <a-form-item label="简介" name="description">
        <a-textarea :rows="5" v-model:value="form.description" placeholder="请输入书签简介（选填）" />
      </a-form-item>
      <a-form-item label="分类" name="categoryId">
        <a-select v-model:value="form.categoryId" placeholder="请选择分类">
          <a-select-option v-for="category in availableCategories" :key="category.key" :value="category.key">
            {{ category.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { GlobalOutlined, LoadingOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  visible: Boolean,
  categories: Array,
  editingBookmark: Object
})

const emit = defineEmits(['update:open', 'submit'])

// 过滤可用的分类（排除"全部"分类）
const availableCategories = computed(() => {
  return props.categories.filter((category) => category.key !== 'all')
})

const form = ref({
  title: '',
  url: '',
  description: '',
  categoryId: ''
})

const resetForm = () => {
  form.value = {
    title: '',
    url: '',
    description: '',
    categoryId: props.editingBookmark?.categoryId || ''
  }
}

const isEditing = computed(() => !!props.editingBookmark?.id)

const previewFavicon = computed(() => {
  try {
    if (!form.value.url) return ''
    const urlObj = new URL(form.value.url)
    return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`
  } catch {
    return null
  }
})

watch(
  () => props.editingBookmark,
  (newVal) => {
    if (newVal) {
      form.value = { ...newVal }
    } else {
      resetForm()
    }
  }
)

watch(
  () => props.visible,
  (newVal) => {
    if (!newVal && !props.editingBookmark) {
      resetForm()
    }
  }
)

const handleOk = () => {
  emit('submit', form.value)
}

const iconRef = ref(null)
const iconFailed = ref(false)

const handleIconError = () => {
  iconFailed.value = true
  if (iconRef.value) {
    iconRef.value.style.display = 'none'
  }
}

const confirmDelete = () => {
  Modal.confirm({
    title: '确定要删除这个书签吗？',
    content: '此操作不可恢复',
    onOk: () => {
      emit('delete')
    }
  })
}
</script>

<style scoped>
.bookmark-preview {
  margin-bottom: 24px;
  padding: 12px;
  background: #fafafa;
  border-radius: var(--border-radius-base);
}

.bookmark-item {
  padding: 12px 10px;
  background: #fff;
  border-radius: var(--border-radius-base);
  transition: all 0.3s;
  width: 220px;
  box-sizing: border-box;
  border: 1px solid #e8e8e8;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 2px;
  height: 82px;
}

.bookmark-item:hover {
  background: #fafafa;
  border-color: #344767;
  transform: translateY(-2px);
}

.bookmark-header {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
  overflow: hidden;
  margin-bottom: 4px;
}

.bookmark-icon {
  width: 28px;
  height: 28px;
  object-fit: contain;
  flex-shrink: 0;
  border-radius: 50%;
  background-color: #f0f0f0;
  padding: 1px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bookmark-title {
  flex: 1;
  font-size: 16px;
  color: #344767;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
  line-height: 1.4;
}

.bookmark-title:hover {
  text-decoration: underline;
}

.bookmark-description {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  flex: 1;
  min-width: 0;
}

.bookmark-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
  padding-top: 6px;
}

.default-icon {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

:deep(.default-icon .anticon) {
  font-size: 14px;
}

.loading-icon {
  background-color: #f5f5f5;
  color: #344767;
}
</style>
